package com.archstudy.springcloud.websocket.http;

import com.archstudy.springcloud.common.constants.SessionConstants;
import com.archstudy.springcloud.common.dto.UserDTO;
import com.archstudy.springcloud.common.result.RestOut;
import com.archstudy.springcloud.common.util.JsonUtil;
import com.google.gson.reflect.TypeToken;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;


public class AppAccountTokenHttpClient {

    private static String account = "1860000000";
    private static   String appToken =

"eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiIxIiwic2lkIjoiOGI4NmFjN2UtYjU3ZS00MzFkLWFiZGYtMjRjYzgxNWE0ZThjIiwiZXhwIjoxNjQ4Mzk0MjA3LCJpYXQiOjE2NTAwOTcxNzV9.ftBJaurTAoTnWWr9e4tJIpoIWmx3QezEtUbovMqTWJRZNr2eCkO35HcSP6tK9RGnSYogrS1N3whAgVsepW0c4XgUWNGL52aRzqVroWyNh8AThjQHkCV0GiY2zWjbuJF8tGvU4TK34GHjMy52aaQCOpzC_gfkSrcoEBDK3A3Hf6fB06X75w5Vt2YGk2kDA2cmHc64TYJlu0YaiC96ndNOOaw6k1Pi2ZfMqC8mNNXoJ3KcC1hOph2o08bhPn-RUzZ436Mt0mveT2s7VTS85d5FXHkkwcEGs0d6K0t8Rz6uMCS8hEj_w9qqtCuka-RXSuwM6VZ_fmdG99brI7M30UYc4Q";
    @Test
    public void getClientAccountToken() {


        String host = "127.0.0.1";
//        String host = "cdh2";
        int port = 7702;
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<Channel>() {

                        @Override
                        protected void initChannel(Channel channel)
                                throws Exception {
                            //channel.pipeline().addLast(new HttpRequestEncoder());
                            //channel.pipeline().addLast(new HttpResponseDecoder());
                            channel.pipeline().addLast(new HttpClientCodec());
                            channel.pipeline().addLast(new HttpObjectAggregator(65536));
                            channel.pipeline().addLast(new HttpContentDecompressor());
                            channel.pipeline().addLast(new HttpClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }


    public class HttpClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        FullHttpRequest request = buildGetRequest();
            FullHttpRequest request = buildPostRequest();
            ctx.writeAndFlush(request);
        }

        private FullHttpRequest buildPostRequest() throws URISyntaxException {

            // *** 生成post传送的uri

            URI uri = new URI("/message-auth-provider/api/auth/account/token/v1");

// *** 设置POST数据包中传输的数据 ***

            String content = "{  \"username\": \"1860000000\"}";

            byte[] bytes = null;

            try {
                bytes = content.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,

                    uri.toASCIIString(), Unpooled.wrappedBuffer(bytes));

            request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");

            request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

            request.headers().set(HttpHeaders.Names.CONTENT_LENGTH,

                    request.content().readableBytes());

            request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
            request.headers().set(SessionConstants.AUTHORIZATION_HEAD, appToken);

            return request;
        }

        private FullHttpRequest buildGetRequest() throws URISyntaxException {
            URI uri = new URI("/user/get");
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri.toASCIIString());
            request.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            request.headers().add(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
            return request;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg)
                throws Exception {
            System.out.println("msg -> " + msg);
            if (msg instanceof FullHttpResponse) {
                FullHttpResponse response = (FullHttpResponse) msg;
                ByteBuf buf = response.content();
                String result = buf.toString(CharsetUtil.UTF_8);
                System.out.println("response -> " + result);
                TypeToken type = new TypeToken<RestOut<UserDTO>>() {
                };
                RestOut<UserDTO> dto=    JsonUtil.jsonToPojo(result, type.getType());
                System.out.println("token -> " );
                System.out.println(dto.getDatas().getToken());

            }
        }
    }
}